package com.knowledge.share.controller;

import com.knowledge.share.pojo.Member;
import com.knowledge.share.pojo.Result;
import com.knowledge.share.service.MemberService;
import com.knowledge.share.utils.EncryptUtils;
import com.knowledge.share.utils.JwtTools;
import com.knowledge.share.utils.ReflectTools;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@Api(tags = "登录注册")
public class AuthController {
    @Autowired
    private MemberService memberService;

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result Login(String username,String password){
        if(username.equals("") || password.equals("")){
            return Result.error("用户名或者密码不能为空");
        }

        try{
            Member user = memberService.getUserByAccount(username);
            if(user == null){
                return Result.error("用户不存在");
            }
            //密码解密然后加密判断信息
            //密码解密md5加密后存入到数据库中
            String pwd = EncryptUtils.decrypt(password);
            password = EncryptUtils.generateMd5(pwd);
            if(!user.getPassword().equals(password)){
                return Result.error("密码错误，请重新输入密码");
            }

            //生成登录后的token值的内容
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtTools.generatorJwtToken(claims);

            HashMap<String, String> data = new HashMap<>();
            data.put("token",token);
            return Result.success("登录成功",data);
        }catch (Exception e){
            log.error("登录失败原因:{}",e.getMessage());
            return Result.error("用户登录失败");
        }
    }

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result Register(@RequestBody Member member){
        if(member.getUsername().equals("") || member.getPassword().equals("")){
            return Result.error("用户名或者密码不能为空");
        }
        //执行简单的注册功能操作
        try {
            //密码解密md5加密后存入到数据库中
            String pwd = EncryptUtils.decrypt(member.getPassword());
            member.setPassword(EncryptUtils.generateMd5(pwd));
            memberService.createUser(member);
        }catch (Exception e){
//            e.printStackTrace();
            log.error("注册失败原因:{}",e.getMessage());
            return Result.error("用户注册失败");
        }
        return Result.success("注册成功");
    }

    /**
     * @desc 获取用户详情信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    @ApiOperation("获取用户信息")
    public Result getInfo(HttpServletRequest request){
        //获取用户token的基本信息
        String token = request.getHeader("Authorization");
        log.info("token的值是:{}",token);

        if(!StringUtils.hasLength(token)){
            return Result.error("token不能为空");
        }
        try {
            //通过token解析获取用户的基本信息
            Claims claims = JwtTools.parseJwtToken(token);
            //类型转换处理
            Integer id = (Integer) claims.get("id");
            Member user = memberService.getUserById(id);
            String[] filters = {"password"};
            HashMap<String,Object> users = ReflectTools.filterEntityField(user,filters);
            return Result.success("获取信息成功",users);
        }catch (Exception e){
            log.error("获取信息失败:{}",e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * @desc 修改用户信息内容
     * @param member
     * @return
     */
    @PutMapping("/info/{id}")
    @ApiOperation("更新用户信息")
    public Result updateInfo(@RequestBody Member member){
        log.info("修改信息对象:{}",member);
        try{
            memberService.updateInfo(member);
            return Result.success("修改信息成功");
        }catch (Exception e){
            log.error("修改信息失败:{}",e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
